package com.itdfq.springboot_shrio.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author GocChin
 * @Date 2021/6/6 15:12
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Descript:
 */
@Controller
public class RounterController {
    @GetMapping({"/index","/"})
    public String test(Model model){
        model.addAttribute("msg","成功");
        return "index";
    }
    @GetMapping("/user/add")
    public String add(){
        return "user/add";
    }
    @GetMapping("/user/update")
    public String update(){
        return "user/update";
    }
    @GetMapping("/tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token); //执行登录方法  如果没有异常就说明登录成功
            return "index";
        }catch (UnknownAccountException e){ //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){//密码错误异常
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauth(){
        return "未经授权，无法访问";
    }

    @RequestMapping("/logout")
    public String logout(){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
//        设置退出登录
        subject.logout();
        return "login";
    }
}
